<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>抓取管理-面试题抓取</title>
    <!-- 引入 Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Font Awesome 图标 -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 自定义 Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#1677ff', // 主色调，类似截图中的蓝色
                        lightBg: '#f5f7fa', // 浅背景色
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    <!-- 自定义工具类 -->
    <style>
        .content-auto {
            content-visibility: auto;
        }

        .sidebar-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1rem;
            border-radius: 0.375rem;
            cursor: pointer;
            transition: all 200ms;
        }

        .sidebar-item.active {
            background-color: #3b82f6;
            color: white;
        }

        .upload-area {
            border: 2px dashed #d1d5db;
            border-radius: 0.375rem;
            padding: 2rem;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 0.75rem;
            cursor: pointer;
            transition: all 200ms;
        }

        .upload-area:hover {
            border-color: #3b82f6;
            background-color: #eff6ff;
        }

        .category-root {
            color: #6b7280;
        }

        .category-child::before {
            content: "— ";
            color: #9ca3af;
            display: inline-block;
            margin-right: 0.25rem;
        }

        .login-button {
            width: 100%;
            padding: 0.75rem;
            border-radius: 0.5rem;
            background-color: #3b82f6;
            color: white;
            font-weight: 500;
            transition: all 200ms;
        }

        .login-button:hover {
            background-color: rgba(59, 130, 246, 0.9);
        }

        .login-button:focus {
            outline: none;
            ring: 2px solid rgba(59, 130, 246, 0.5);
            ring-offset: 2px;
        }

        /* 弹窗动画类 */
        .scale-95 {
            transform: scale(0.95);
            transition: transform 0.2s ease-out;
        }

        .scale-100 {
            transform: scale(1);
            transition: transform 0.2s ease-out;
        }
    </style>
</head>

<body class="bg-lightBg min-h-screen flex">
    <!-- 登录弹窗 HTML -->
    <div id="loginModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-gray-800">用户登录</h2>
                <button id="closeLoginModalBtn" class="text-gray-500 hover:text-gray-700 focus:outline-none">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <form id="loginForm" class="space-y-4">
                <div>
                    <label for="loginUsername" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <input type="text" id="loginUsername" name="username"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                        placeholder="请输入用户名" required>
                </div>
                <div>
                    <label for="loginPassword" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                    <input type="password" id="loginPassword" name="password"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                        placeholder="请输入密码" required>
                </div>
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <input type="checkbox" id="rememberMe" name="rememberMe"
                            class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                        <label for="rememberMe" class="ml-2 block text-sm text-gray-700">记住我</label>
                    </div>
                    <a href="#" class="text-sm text-blue-600 hover:text-blue-800">忘记密码?</a>
                </div>
                <button type="submit"
                    class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                    登录
                </button>
            </form>
        </div>
    </div>
    <!-- 登录弹窗样式 -->
    <style>
        /* 登录按钮样式 */
        .login-button {
            background-color: #1E40AF;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 0.25rem;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .login-button:hover {
            background-color: #1E3A8A;
        }

        /* 侧边栏项样式 */
        .sidebar-item {
            display: flex;
            align-items: center;
            padding: 0.75rem 1rem;
            color: #6B7280;
            transition: all 0.2s;
            border-radius: 0.375rem;
            text-decoration: none;
        }

        .sidebar-item:hover {
            background-color: #F3F4F6;
            color: #1F2937;
        }

        .sidebar-item.active {
            background-color: #3B82F6;
            color: white;
        }

        .sidebar-item i {
            margin-right: 0.5rem;
            width: 1.5rem;
            text-align: center;
        }
    </style>
    <!-- 登录弹窗交互脚本 -->
    <script>
        // 显示登录弹窗
        document.getElementById('showLoginModalBtn')?.addEventListener('click', function () {
            document.getElementById('loginModal').classList.remove('hidden');
        });

        // 关闭登录弹窗
        document.getElementById('closeLoginModalBtn')?.addEventListener('click', function () {
            document.getElementById('loginModal').classList.add('hidden');
        });

        // 点击弹窗外部关闭弹窗
        document.getElementById('loginModal')?.addEventListener('click', function (e) {
            if (e.target === this) {
                this.classList.add('hidden');
            }
        });

        // 登录表单提交
        document.getElementById('loginForm')?.addEventListener('submit', function (e) {
            e.preventDefault();

            // 模拟登录成功
            const username = document.getElementById('loginUsername').value;

            // 存储登录状态到本地存储
            localStorage.setItem('isLoggedIn', 'true');
            localStorage.setItem('username', username);

            // 关闭弹窗
            document.getElementById('loginModal').classList.add('hidden');

            // 更新UI显示
            updateLoginUI();

            // 显示登录成功提示
            alert('登录成功！');
        });

        // 退出登录功能
        document.getElementById('logoutLink')?.addEventListener('click', function (e) {
            e.preventDefault();

            // 清除登录状态
            localStorage.removeItem('isLoggedIn');
            localStorage.removeItem('username');

            // 更新UI显示
            updateLoginUI();

            // 显示退出成功提示
            alert('退出成功！');
        });

        // 更新登录UI状态
        function updateLoginUI() {
            const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
            const username = localStorage.getItem('username');

            // 更新登录按钮显示
            const loginButton = document.getElementById('showLoginModalBtn');

            // 更新退出登录项显示
            const logoutItem = document.querySelector('.logout-item');

            if (isLoggedIn) {
                if (loginButton) {
                    loginButton.style.display = 'none';
                }
                if (logoutItem) {
                    logoutItem.classList.remove('hidden');
                }
            } else {
                if (loginButton) {
                    loginButton.style.display = 'block';
                }
                if (logoutItem) {
                    logoutItem.classList.add('hidden');
                }
            }
        }

        // 页面加载时检查登录状态
        document.addEventListener('DOMContentLoaded', function () {
            updateLoginUI();
        });
    </script>
    <!-- 侧边栏 -->
    <aside class="w-64 bg-white shadow-md">
        <div class="p-4">
            <h1 class="text-2xl font-bold text-gray-800">会员中心</h1>
            <!-- 登录按钮 -->
            <button id="showLoginModalBtn" class="login-button w-full mt-4">
                <i class="fa fa-sign-in mr-2"></i> 立即登录
            </button>
        </div>
        <nav class="mt-4">
            <ul>
                <li>
                    <a href="index.html" class="sidebar-item">
                        <i class="fa fa-cloud-upload"></i>
                        上传文档
                    </a>
                </li>
                <!-- 新增：文档管理 菜单项 -->
                <li>
                    <a href="documents.html" class="sidebar-item" id="documentsLink">
                        <i class="fa fa-folder-open"></i> <!-- 使用文件夹打开图标，与文档管理语义匹配 -->
                        文档管理
                    </a>
                </li>
                <!-- 新增：公众号管理 菜单项 -->
                <li>
                    <a href="wechat-accounts.html" class="sidebar-item">
                        <i class="fa fa-weixin"></i>
                        公众号管理
                    </a>
                </li>
                <!-- 新增：账号管理 菜单项 -->
                <li>
                    <a href="wechat-account-management.html" class="sidebar-item">
                        <i class="fa fa-user-circle-o"></i>
                        账号管理
                    </a>
                </li>
                <!-- 新增：抓取管理 菜单项 -->
                <li>
                    <a href="scraping.html" class="sidebar-item active">
                        <i class="fa fa-scissors"></i>
                        抓取管理
                    </a>
                </li>
                <!-- 新增：数据库配置 菜单项 -->
                <li>
                    <a href="database-config.html" class="sidebar-item">
                        <i class="fa fa-database"></i>
                        数据库配置
                    </a>
                </li>
                <!-- 新增：发布管理 菜单项 -->
                <li>
                    <a href="publish-management.html" class="sidebar-item">
                        <i class="fa fa-paper-plane"></i>
                        发布管理
                    </a>
                </li>
                <li class="logout-item hidden">
                    <a href="#" class="sidebar-item" id="logoutLink">
                        <i class="fa fa-sign-out"></i>
                        退出登录
                    </a>
                </li>
            </ul>
        </nav>
    </aside>

    <!-- 主内容区 -->
    <main class="flex-1 p-8">
        <div class="grid grid-cols-12 gap-8">
            <!-- 抓取管理表单区域 -->
            <div class="col-span-12 bg-white rounded-lg shadow-md p-6">
                <div class="flex items-center justify-between mb-6">
                    <h2 class="text-xl font-bold text-gray-800">面试题抓取</h2>
                    <button id="openMaterialLibBtn"
                        class="px-6 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700">
                        <i class="fa fa-th mr-2"></i>打开素材库
                    </button>
                </div>

                <!-- 网站选择区域 -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">选择抓取网站</label>
                    <div class="flex flex-wrap gap-4">
                        <button id="niukeBtn" class="px-4 py-2 rounded bg-primary text-white">
                            <i class="fa fa-bullhorn mr-2"></i>牛客网
                        </button>
                        <button id="niumianBtn" class="px-4 py-2 rounded text-gray-600 border border-gray-300">
                            <i class="fa fa-comments-o mr-2"></i>牛面网
                        </button>
                    </div>
                    <p id="siteHint" class="mt-2 text-sm text-gray-500">当前选择：牛客网 (不同网站抓取规则不同)</p>
                </div>

                <!-- URL输入区域 -->
                <div class="mb-6">
                    <label for="urlInput" class="block text-sm font-medium text-gray-700 mb-2">输入面试题URL</label>
                    <div class="flex">
                        <input type="text" id="urlInput" placeholder="请输入要抓取的面试题URL"
                            class="flex-1 px-4 py-2 border border-gray-300 rounded-l-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary">
                        <button id="scrapeBtn" class="px-6 py-2 bg-primary text-white rounded-r-md hover:bg-primary/90">
                            <i class="fa fa-magnet mr-2"></i>开始抓取
                        </button>
                    </div>
                </div>

                <!-- 抓取状态显示区域 -->
                <div id="scrapeStatus" class="mb-6 hidden">
                    <div class="p-4 bg-blue-50 rounded-md">
                        <div class="flex items-center">
                            <i class="fa fa-circle-o-notch fa-spin text-primary mr-3"></i>
                            <p id="scrapeStatusText">正在抓取内容...</p>
                        </div>
                    </div>
                </div>

                <!-- 抓取结果区域 -->
                <div id="scrapeResult" class="mb-6 hidden">
                    <h3 class="text-lg font-medium text-gray-800 mb-4">抓取结果</h3>

                    <!-- 标题输入 -->
                    <div class="mb-4">
                        <label for="title" class="block text-sm font-medium text-gray-700 mb-2">标题</label>
                        <input type="text" id="title"
                            class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary"
                            readonly>
                    </div>

                    <!-- 分类选择 -->
                    <div class="mb-4">
                        <label for="categorySelect" class="block text-sm font-medium text-gray-700 mb-2">面试题分类</label>
                        <select id="categorySelect"
                            class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary bg-white">
                            <option value="">请选择分类</option>
                            <option value="91">
                                <i class="fa fa-database mr-2"></i>数据库
                            </option>
                            <option value="92">
                                <i class="fa fa-code mr-2"></i>大前端
                            </option>
                            <option value="93">
                                <i class="fa fa-robot mr-2"></i>人工智能
                            </option>
                        </select>
                    </div>

                    <!-- 内容预览 -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">内容预览</label>
                        <div id="contentPreview"
                            class="p-4 border border-gray-300 rounded-md h-48 overflow-y-auto text-gray-700">
                            <!-- 预览内容将在这里显示 -->
                        </div>
                    </div>

                    <!-- 生成Word和上传按钮 -->
                    <div class="flex gap-4">
                        <button id="generateWordBtn"
                            class="px-6 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">
                            <i class="fa fa-file-word-o mr-2"></i>生成Word
                        </button>
                        <button id="uploadBtn" class="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                            <i class="fa fa-upload mr-2"></i>上传到素材库
                        </button>
                    </div>
                </div>

                <!-- 素材库弹窗 -->
                <div id="materialLibModal"
                    class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
                    <div class="bg-white rounded-lg shadow-xl w-full max-w-4xl max-h-[90vh] flex flex-col">
                        <!-- 弹窗头部 -->
                        <div class="p-4 border-b border-gray-200 flex justify-between items-center">
                            <h3 class="text-xl font-bold text-gray-800">素材库</h3>
                            <button id="closeMaterialLibBtn" class="text-gray-500 hover:text-gray-700">
                                <i class="fa fa-times text-xl"></i>
                            </button>
                        </div>

                        <!-- 弹窗内容 -->
                        <div class="p-4 overflow-y-auto flex-grow">
                            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4" id="materialGrid">
                                <!-- 素材项将通过JavaScript动态生成 -->
                            </div>
                        </div>

                        <!-- 弹窗底部 -->
                        <div class="p-4 border-t border-gray-200 flex justify-end gap-3">
                            <button id="cancelMaterialSelectBtn"
                                class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300">
                                取消
                            </button>
                            <button id="confirmMaterialSelectBtn"
                                class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90">
                                确认插入选中素材
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 上传进度条 -->
                <div id="progressContainer" class="mt-4 hidden">
                    <div class="flex justify-between items-center mb-1">
                        <span class="text-sm text-gray-600">上传进度</span>
                        <span id="progressPercent" class="text-sm font-medium">0%</span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2">
                        <div id="progressBar" class="bg-primary h-2 rounded-full" style="width: 0%"></div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <script>
        // 登录弹窗相关
        const loginModal = document.getElementById('loginModal');
        const showLoginModalBtn = document.getElementById('showLoginModalBtn');
        const closeModalBtn = document.getElementById('closeLoginModalBtn');
        const loginForm = document.getElementById('loginForm');
        const loginUsername = document.getElementById('loginUsername');
        const loginPassword = document.getElementById('loginPassword');

        // 点击登录按钮跳转到登录页面
        showLoginModalBtn.addEventListener('click', () => {
            window.location.href = '/login.html';
        });

        // 关闭登录弹窗
        if (closeModalBtn) {
            closeModalBtn.addEventListener('click', () => {
                loginModal.querySelector('div').classList.remove('scale-100');
                loginModal.querySelector('div').classList.add('scale-95');
                setTimeout(() => {
                    loginModal.classList.add('hidden');
                }, 200);
            });
        }

        // 登录请求
        loginForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const username = loginUsername.value.trim();
            const password = loginPassword.value.trim();

            if (!username || !password) {
                alert('用户名和密码不能为空');
                return;
            }

            // 模拟登录请求
            fetch('/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0) {
                        // 登录成功
                        localStorage.setItem('isLoggedIn', 'true');
                        localStorage.setItem('username', username);
                        closeModalBtn.click();
                        updateLoginStatus();
                        alert('登录成功！');
                    } else {
                        alert(data.message || '登录失败，请检查用户名和密码');
                    }
                })
                .catch(error => {
                    alert('网络错误，请稍后重试');
                    console.error('Login error:', error);
                });
        });

        // 检查登录状态
        function checkLoginStatus() {
            return new Promise((resolve) => {
                // 无论localStorage中是否有登录状态，都向服务器验证真实的登录状态
                console.log('发送请求到服务器验证登录状态');

                // 否则，发送网络请求检查登录状态
                console.log('localStorage中没有有效的登录状态，发送请求到服务器');

                fetch('/check-login', {
                    method: 'GET',
                    credentials: 'same-origin'
                })
                    .then(response => {
                        console.log('check-login响应状态:', response.status);
                        if (!response.ok) {
                            // 即使响应状态不是200，也尝试解析JSON
                            return response.json().catch(() => {
                                throw new Error(`Network response was not ok: ${response.status}`);
                            });
                        }
                        return response.json();
                    })
                    .then(data => {
                        console.log('check-login响应数据:', data);
                        // 返回完整的数据对象，包括isLoggedIn和username
                        if (data.isLoggedIn && data.username) {
                            // 如果登录状态有效，保存到localStorage
                            localStorage.setItem('isLoggedIn', 'true');
                            localStorage.setItem('username', data.username);
                        }
                        resolve(data);
                    })
                    .catch(error => {
                        console.error('检查登录状态请求失败:', error.message || error);
                        // 请求失败时，不应该信任localStorage，返回未登录状态
                        // 清除localStorage中的登录信息
                        localStorage.removeItem('isLoggedIn');
                        localStorage.removeItem('username');
                        resolve({ isLoggedIn: false, username: null });
                    });
            });
        }

        // 根据登录状态更新界面
        async function updateLoginStatus() {
            const loginButton = document.querySelector('.login-button');
            if (!loginButton) {
                return;
            }

            const loginStatus = await checkLoginStatus();
            const logoutItem = document.querySelector('.logout-item');

            if (loginStatus.isLoggedIn && loginStatus.username) {
                // 已登录，替换登录按钮为欢迎信息
                // 显示退出登录选项
                if (logoutItem) {
                    logoutItem.classList.remove('hidden');
                }
                const welcomeElement = document.createElement('div');
                welcomeElement.className = 'text-center text-gray-600 mt-4 px-4';
                welcomeElement.innerHTML = `<p class="font-medium">欢迎您，${loginStatus.username}</p><a id="logoutLink" href="#" class="text-sm text-blue-500 hover:text-blue-700 mt-1 inline-block">退出登录</a>`;
                loginButton.parentNode.replaceChild(welcomeElement, loginButton);

                // 重新绑定退出登录事件
                document.getElementById('logoutLink').addEventListener('click', function (e) {
                    e.preventDefault();
                    if (confirm('确定要退出登录吗？')) {
                        fetch('/logout', {
                            method: 'POST'
                        })
                            .then(response => response.json())
                            .then(data => {
                                // 无论服务器返回什么结果，都清除localStorage中的登录状态
                                localStorage.removeItem('isLoggedIn');
                                localStorage.removeItem('username');

                                if (data.code === 0) {
                                    // 刷新页面以更新登录状态
                                    window.location.reload();
                                } else {
                                    alert('退出登录失败，请重试');
                                    // 即使服务器返回失败，也刷新页面
                                    window.location.reload();
                                }
                            })
                            .catch(error => {
                                alert('网络错误，请稍后重试');
                                // 即使网络请求失败，也清除localStorage并刷新页面
                                localStorage.removeItem('isLoggedIn');
                                localStorage.removeItem('username');
                                window.location.reload();
                            });
                    }
                });
            } else {
                // 未登录，隐藏退出登录选项
                if (logoutItem) {
                    logoutItem.classList.add('hidden');
                }
            }
        }

        // 页面加载时更新登录状态
        document.addEventListener('DOMContentLoaded', () => {
            updateLoginStatus();
            initScrapingFunctions();
        });

        // 初始化抓取功能
        function initScrapingFunctions() {
            // 网站选择按钮
            const niukeBtn = document.getElementById('niukeBtn');
            const niumianBtn = document.getElementById('niumianBtn');
            const siteHint = document.getElementById('siteHint');
            let currentSite = 'niuke'; // 默认选择牛客网

            // 网站选择切换
            niukeBtn.addEventListener('click', () => {
                currentSite = 'niuke';
                niukeBtn.className = 'px-4 py-2 rounded bg-primary text-white';
                niumianBtn.className = 'px-4 py-2 rounded text-gray-600 border border-gray-300';
                siteHint.textContent = '当前选择：牛客网 (不同网站抓取规则不同)';
            });

            niumianBtn.addEventListener('click', () => {
                currentSite = 'niumian';
                niumianBtn.className = 'px-4 py-2 rounded bg-primary text-white';
                niukeBtn.className = 'px-4 py-2 rounded text-gray-600 border border-gray-300';
                siteHint.textContent = '当前选择：牛面网 (不同网站抓取规则不同)';
            });

            // 分类选择下拉条
            const categorySelect = document.getElementById('categorySelect');
            let selectedCategoryId = null;

            categorySelect.addEventListener('change', () => {
                selectedCategoryId = categorySelect.value;
            });

            // 抓取按钮点击事件
            const scrapeBtn = document.getElementById('scrapeBtn');
            const urlInput = document.getElementById('urlInput');
            const scrapeStatus = document.getElementById('scrapeStatus');
            const scrapeStatusText = document.getElementById('scrapeStatusText');
            const scrapeResult = document.getElementById('scrapeResult');
            const titleInput = document.getElementById('title');
            const contentPreview = document.getElementById('contentPreview');

            scrapeBtn.addEventListener('click', async () => {
                const url = urlInput.value.trim();
                if (!url) {
                    alert('请输入要抓取的URL');
                    return;
                }

                // 显示抓取状态
                scrapeStatus.classList.remove('hidden');
                scrapeStatusText.textContent = '正在抓取内容...';
                scrapeResult.classList.add('hidden');

                // 检查登录状态
                const loginStatus = await checkLoginStatus();
                if (!loginStatus.isLoggedIn) {
                    scrapeStatus.classList.add('hidden');
                    showLoginModalBtn.click();
                    return;
                }

                try {
                    // 调用后端API进行实际抓取
                    scrapeStatusText.textContent = '正在发送抓取请求...';
                    // 确保URL是纯文本格式，没有额外的引号或反引号
                    const cleanUrl = url.replace(/[`"']/g, '').trim();
                    const response = await fetch('/api/crawl', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            url: cleanUrl,
                            site: currentSite
                        })
                    });

                    scrapeStatusText.textContent = '正在解析抓取结果...';
                    const result = await response.json();

                    if (result.success) {
                        // 更新UI - 使用questions字段而不是content字段
                    titleInput.value = result.title || '未获取到标题';
                    
                    // 解析转义后的JSON字符串
                    let questionsText = result.questions || '未获取到内容';
                    try {
                        // 使用更可靠的方法解码JSON字符串
                        // 先将字符串包装成JSON格式，然后解析它
                        const wrappedJson = '"' + questionsText.replace(/"/g, '\\"') + '"';
                        const decodedString = JSON.parse(wrappedJson);
                        contentPreview.textContent = decodedString;
                    } catch (e) {
                        // 如果解码失败，尝试简单的文本替换
                        try {
                            const decodedString = questionsText
                                .replace(/\\n/g, '\n')
                                .replace(/\\r/g, '\r')
                                .replace(/\\t/g, '\t')
                                .replace(/\\"/g, '"')
                                .replace(/\\\\/g, '\\');
                            contentPreview.textContent = decodedString;
                        } catch (innerError) {
                            // 如果两种方法都失败，直接使用原始文本
                            contentPreview.textContent = questionsText;
                            console.error('解析内容失败:', innerError);
                        }
                    }
                        scrapeStatus.classList.add('hidden');
                        scrapeResult.classList.remove('hidden');
                    } else {
                        throw new Error(result.error || '抓取失败，未知错误');
                    }
                } catch (error) {
                    scrapeStatusText.textContent = '抓取失败：' + error.message;
                    setTimeout(() => {
                        scrapeStatus.classList.add('hidden');
                    }, 2000);
                }
            });

            // 生成Word文档的函数
            function generateWordDocument(title, content) {
                return new Promise((resolve) => {
                    // 模拟生成Word过程
                    const statusDiv = document.createElement('div');
                    statusDiv.className = 'fixed top-4 right-4 bg-green-600 text-white px-4 py-2 rounded-md shadow-lg z-50';
                    statusDiv.textContent = '正在生成Word文档...';
                    document.body.appendChild(statusDiv);

                    // 模拟生成Word的延迟
                    setTimeout(() => {
                        statusDiv.textContent = 'Word文档生成成功';
                        setTimeout(() => {
                            document.body.removeChild(statusDiv);
                        }, 1000);
                    }, 1000);

                    // 处理代码块，添加语法高亮支持
                    // 1. 检测并提取代码块（寻找```或类似的代码块标记）
                    // 2. 使用HTML格式创建一个Word兼容的文档结构
                    const htmlContent = formatContentWithCodeHighlighting(title, content);

                    // 创建HTML格式的Blob对象（Word可以很好地解析HTML格式）
                    const blob = new Blob([htmlContent], { type: 'application/msword' });
                    const fileName = `${title}.doc`;

                    // 使用File构造函数创建文件对象
                    const file = new File([blob], fileName, { type: 'application/msword' });

                    // 延迟返回以匹配UI提示
                    setTimeout(() => resolve(file), 1500);
                });
            }

            // 格式化内容，为代码添加语法高亮支持
            function formatContentWithCodeHighlighting(title, content) {
                // 基础HTML文档结构，Word可以识别
                let html = `<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>${title}</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            line-height: 1.6;
            margin: 20px;
        }
        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
            font-size: 20pt;
            font-weight: bold;
        }
        p {
            margin: 10px 0;
            text-indent: 2em;
        }
        pre {
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: 4px;
            overflow-x: auto;
            font-family: 'Courier New', monospace;
            white-space: pre-wrap;
            margin: 15px 0;
        }
        code {
            font-family: 'Courier New', monospace;
            background-color: #f5f5f5;
            padding: 2px 4px;
            border-radius: 3px;
            font-size: 10pt;
        }
        .question {
            font-weight: bold;
            color: #2c3e50;
            margin-top: 20px;
        }
        .answer {
            color: #34495e;
            margin-left: 20px;
        }
    </style>
</head>
<body>
    <h1>${escapeHtml(title)}</h1>`;

                // 处理内容，识别并格式化代码块
                // 1. 识别并处理行内代码（`code` 格式）
                content = content.replace(/`([^`]+)`/g, '<code>$1</code>');

                // 2. 识别并处理多行代码块（```code``` 格式）
                const codeBlockRegex = /```([\s\S]*?)```/g;
                let match;
                let lastIndex = 0;
                const formattedParts = [];

                while ((match = codeBlockRegex.exec(content)) !== null) {
                    // 添加代码块之前的内容
                    if (match.index > lastIndex) {
                        formattedParts.push(escapeHtml(content.substring(lastIndex, match.index)));
                    }
                    // 添加格式化的代码块
                    formattedParts.push(`<pre>${escapeHtml(match[1])}</pre>`);
                    lastIndex = match.index + match[0].length;
                }

                // 添加剩余内容
                if (lastIndex < content.length) {
                    formattedParts.push(escapeHtml(content.substring(lastIndex)));
                }

                // 组合所有内容部分
                const processedContent = formattedParts.join('');

                // 为面试题添加特殊格式（如果内容包含"问题"或类似标记）
                const lines = processedContent.split('\n');
                for (let i = 0; i < lines.length; i++) {
                    let line = lines[i].trim();
                    if (line.startsWith('问题') ||
                        line.match(/^\d+\.\s*问题/) ||
                        line.match(/^\d+\.\s*题目/) ||
                        line.match(/^问题\d+：/)) {
                        html += `<div class="question">${line}</div>`;
                    } else if (line.startsWith('答案') || line.startsWith('解析')) {
                        html += `<div class="answer">${line}</div>`;
                    } else if (line) {
                        html += `<p>${line}</p>`;
                    } else {
                        html += '<br/>';
                    }
                }

                html += `
</body>
</html>`;
                return html;
            }

            // 转义HTML特殊字符
            function escapeHtml(text) {
                const div = document.createElement('div');
                div.textContent = text;
                return div.innerHTML;
            }

            // 生成Word按钮点击事件（保留原有功能）
            const generateWordBtn = document.getElementById('generateWordBtn');

            generateWordBtn.addEventListener('click', async () => {
                const title = titleInput.value.trim();
                const content = contentPreview.textContent.trim();

                if (!title || !content) {
                    alert('请先完成抓取，确保有标题和内容');
                    return;
                }

                // 生成Word文档
                await generateWordDocument(title, content);
            });

            // 上传按钮点击事件 - 只保存到素材库
            const uploadBtn = document.getElementById('uploadBtn');
            const progressContainer = document.getElementById('progressContainer');
            const progressBar = document.getElementById('progressBar');
            const progressPercent = document.getElementById('progressPercent');

            // 上传Word文档到服务器并获取七牛云URL
            async function uploadWordToServerAndGetQiniuUrl(title, content) {
                try {
                    // 生成Word文档
                    const wordFile = await generateWordDocument(title, content);
                    progressBar.style.width = '30%';
                    progressPercent.textContent = '30%';

                    // 创建FormData对象
                    const formData = new FormData();
                    formData.append('file', wordFile);
                    formData.append('title', title);
                    
                    // 上传到服务器
                    const uploadResponse = await fetch('/uploadWordForMaterial', {
                        method: 'POST',
                        body: formData
                    });
                    progressBar.style.width = '70%';
                    progressPercent.textContent = '70%';

                    // 解析响应
                    const uploadResult = await uploadResponse.json();
                    
                    if (!uploadResult.success) {
                        throw new Error('文件上传失败：' + uploadResult.message);
                    }

                    return uploadResult.qiniuUrl;
                } catch (error) {
                    console.error('上传Word文档到服务器失败:', error);
                    throw error;
                }
            }

            uploadBtn.addEventListener('click', async () => {
                const title = titleInput.value.trim();
                const content = contentPreview.textContent.trim();
                const category = selectedCategoryId;

                if (!title || !content) {
                    alert('请先完成抓取，确保有标题和内容');
                    return;
                }

                if (!category) {
                    alert('请选择面试题分类');
                    return;
                }

                // 检查登录状态
                const loginStatus = await checkLoginStatus();
                if (!loginStatus.isLoggedIn) {
                    showLoginModalBtn.click();
                    return;
                }

                // 显示进度条
                progressContainer.classList.remove('hidden');
                progressBar.style.width = '0%';
                progressPercent.textContent = '0%';

                // 禁用上传按钮防止重复提交
                uploadBtn.disabled = true;
                uploadBtn.textContent = '保存中...';

                try {
                    // 先生成Word文档并上传到服务器获取七牛云URL
                    const qiniuUrl = await uploadWordToServerAndGetQiniuUrl(title, content);
                     
                    // 更新进度条
                    progressBar.style.width = '90%';
                    progressPercent.textContent = '90%';

                    // 使用七牛云URL作为content参数发送请求保存到素材库
                    const response = await fetch('/api/saveToMaterial', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            title: title,
                            content: qiniuUrl, // 使用七牛云URL作为content参数
                            categoryId: category,
                            sourceUrl: urlInput.value.trim()
                        })
                    });

                    // 更新进度条
                    progressBar.style.width = '100%';
                    progressPercent.textContent = '100%';

                    // 处理响应
                    const result = await response.json();

                    // 启用上传按钮
                    uploadBtn.disabled = false;
                    uploadBtn.textContent = '上传到素材库';

                    // 隐藏进度条
                    progressContainer.classList.add('hidden');

                    if (result.success) {
                        alert('保存到素材库成功！ID: ' + result.id + ' ' + result.message);
                    } else {
                        alert('保存到素材库失败：' + result.message);
                    }
                } catch (error) {
                    uploadBtn.disabled = false;
                    uploadBtn.textContent = '上传到素材库';
                    progressContainer.classList.add('hidden');
                    alert('保存过程中出错：' + error.message);
                }
            });

            // 素材库相关功能
            const materialLibModal = document.getElementById('materialLibModal');
            const openMaterialLibBtn = document.getElementById('openMaterialLibBtn');
            const closeMaterialLibBtn = document.getElementById('closeMaterialLibBtn');
            const cancelMaterialSelectBtn = document.getElementById('cancelMaterialSelectBtn');
            const confirmMaterialSelectBtn = document.getElementById('confirmMaterialSelectBtn');
            const materialGrid = document.getElementById('materialGrid');

            // 存储选中的素材
            let selectedMaterials = [];

            // 打开素材库弹窗
            openMaterialLibBtn.addEventListener('click', async () => {
                // 检查登录状态
                const loginStatus = await checkLoginStatus();
                if (!loginStatus.isLoggedIn) {
                    showLoginModalBtn.click();
                    return;
                }

                // 清空选中的素材
                selectedMaterials = [];

                // 加载素材库数据（这里使用模拟数据）
                loadMaterialLibrary();

                // 显示弹窗
                materialLibModal.classList.remove('hidden');
            });

            // 关闭素材库弹窗
            function closeMaterialLibModal() {
                materialLibModal.classList.add('hidden');
            }

            closeMaterialLibBtn.addEventListener('click', closeMaterialLibModal);
            cancelMaterialSelectBtn.addEventListener('click', closeMaterialLibModal);

            // 点击弹窗外部关闭弹窗
            materialLibModal.addEventListener('click', (e) => {
                if (e.target === materialLibModal) {
                    closeMaterialLibModal();
                }
            });

            // 加载素材库数据
            async function loadMaterialLibrary() {
                // 清空素材网格
                materialGrid.innerHTML = '<div class="text-center py-10 text-gray-500">加载中...</div>';

                try {
                    // 调用API获取素材库数据
                    const response = await fetch('/api/materials');
                    if (!response.ok) {
                        throw new Error('服务器响应错误');
                    }

                    const result = await response.json();

                    // 清空素材网格
                    materialGrid.innerHTML = '';

                    // 检查响应状态码
                    if (result.code !== 0) {
                        throw new Error('获取素材失败: ' + result.message);
                    }

                    // 获取素材数组
                    const materials = result.data || [];

                    if (materials.length === 0) {
                        materialGrid.innerHTML = '<div class="text-center py-10 text-gray-500">暂无素材数据</div>';
                        return;
                    }

                    // 添加素材项
                    materials.forEach(material => {
                        const materialItem = document.createElement('div');
                        materialItem.className = 'border border-gray-200 rounded-md p-4 hover:border-primary transition-colors cursor-pointer';
                        materialItem.dataset.id = material.id;

                        const materialTitle = document.createElement('h4');
                        materialTitle.className = 'font-semibold text-gray-800 mb-2';
                        materialTitle.textContent = material.title;

                        const materialContent = document.createElement('p');
                        materialContent.className = 'text-sm text-gray-600 line-clamp-3';
                        materialContent.textContent = material.content;

                        const checkbox = document.createElement('div');
                        checkbox.className = 'mt-3 flex items-center';
                        checkbox.innerHTML = `<input type="checkbox" id="material-${material.id}" class="mr-2">
                                         <label for="material-${material.id}" class="text-sm text-gray-700">选择此素材</label>`;

                        materialItem.appendChild(materialTitle);
                        materialItem.appendChild(materialContent);
                        materialItem.appendChild(checkbox);

                        // 添加点击事件
                        materialItem.addEventListener('click', (e) => {
                            const checkbox = materialItem.querySelector('input[type="checkbox"]');
                            checkbox.checked = !checkbox.checked;
                            updateSelectedMaterials();
                        });

                        // 复选框的点击事件（阻止冒泡）
                        checkbox.addEventListener('click', (e) => {
                            e.stopPropagation();
                            updateSelectedMaterials();
                        });

                        materialGrid.appendChild(materialItem);
                    });
                } catch (error) {
                    console.error('加载素材库失败:', error);
                    materialGrid.innerHTML = '<div class="text-center py-10 text-red-500">加载素材库失败，请稍后重试</div>';
                }
            }

            // 更新选中的素材列表
            function updateSelectedMaterials() {
                selectedMaterials = [];
                const checkboxes = document.querySelectorAll('#materialGrid input[type="checkbox"]:checked');

                checkboxes.forEach(checkbox => {
                    const materialItem = checkbox.closest('[data-id]');
                    const materialId = parseInt(materialItem.dataset.id);
                    const materialTitle = materialItem.querySelector('h4').textContent;
                    const materialContent = materialItem.querySelector('p').textContent;

                    selectedMaterials.push({ id: materialId, title: materialTitle, content: materialContent });
                });
            }

            // 确认插入选中的素材
            confirmMaterialSelectBtn.addEventListener('click', async () => {
                if (selectedMaterials.length === 0) {
                    alert('请至少选择一个素材');
                    return;
                }

                // 随机排序选中的素材
                const shuffledMaterials = [...selectedMaterials].sort(() => Math.random() - 0.5);

                try {
                    // 调用API将素材插入到文库表中
                    console.log('准备插入素材:', shuffledMaterials);
                    
                    const response = await fetch('/api/insert-materials', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            materials: shuffledMaterials
                        })
                    });
                    
                    if (!response.ok) {
                        throw new Error('服务器响应错误');
                    }
                    
                    const result = await response.json();
                    
                    if (result.code === 0) {
                        alert(`已成功将${result.successCount}/${result.totalCount}个素材以随机顺序插入到wenku和file表中`);
                        // 关闭弹窗
                        closeMaterialLibModal();
                    } else {
                        throw new Error(result.message || '插入素材失败');
                    }
                } catch (error) {
                    console.error('插入素材失败:', error);
                    alert('插入素材失败，请稍后重试');
                }
            });
        }
    </script>
</body>

996|

</html>